<template>
  <div class="user-status-content"
  style="display: flex;flex-direction: column; "
       v-loading="loadingUserDataLists"
       :element-loading-text="$t('loading')"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(255, 255, 255, 0.8)">
    <div class="search-area">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select v-model="searchForm.managerId"
                     @change="managerIdChange"
                     filterable
                     clearable
                     :placeholder="$t('custom.attendance.record.search.manager')"
                     style="width:100%;">
            <el-option v-for="(item,i) in managerList"
                       :key="i"
                       :label="item.realName"
                       :value="item.managerId">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-checkbox style="margin-bottom: 8px;margin-top: 8px;"
                       v-model="searchForm.recursive"
                       @change="recursiveChange">{{ $t('custom.attendance.record.search.recursive') }}</el-checkbox>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.member"
                     @change="memberChange"
                     filterable
                     multiple
                     collapse-tags
                     clearable
                     :placeholder="$t('custom.attendance.record.search.member')"
                     style="width:100%;">
            <el-option v-for="(item,ii) in memberLists"
                       :key="ii"
                       :label="item.realName"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button size="small"
                     type="primary"
                     v-if="$hasPermission('sys:bots:psastatussetting')"
                     @click="openPSASetupDialog()">{{ $t('custom.bots.psaStatusSetting') }}
          </el-button>
        </el-col>
        <el-col :span="4" style="float:right;margin-right:10px">
          <div class="sort-select" v-loading="loadingUserDataLists">
            <div class="label">Sort</div>
            <el-select v-model="curSortS"
                      style="margin:0 10px;"
                      size="mini"
                      @change="changeSortS">
              <el-option v-for="(item,ii) in sortList"
                        :key="ii"
                        :label="item.dictLabel"
                        :value="item.dictValue">
              </el-option>
          </el-select>
          <el-button size="mini" @click="changeSortB" :icon="curSortB==='Asc'?'el-icon-top':'el-icon-bottom'"></el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class='list scroll-css'
         style="margin-top: 10px;flex: 1;height: 0;">
      <div class="list-item"
           v-for="item in userDataLists"
           :key="item.userid">
        <div :style="{ background: backgroundformat(item.action, item.subAction, item.timeout)}"
             style="width:100%;height:100%;">
          <div style="display: flex; padding: 5px 5px 0px 5px;">
            <div>
              <el-avatar :size="40"
                         :src="item.headerUrl ? item.headerUrl : ''">
                <!-- $store.getters.prodOssLink + item.teamsUserId + '.jpg'
                :src="item.teamsUserId ? `${$store.state.app.prodOssLink}${item.teamsUserId}.jpg` : ''">
                 -->
                <template slot="default">
                  <div style="white-space: nowrap; overflow: hidden;">
                    {{ avatarFormat(item.username) }}
                  </div>
                </template>
              </el-avatar>
            </div>
            <div style="padding-left: 10px; color: white; display: flex; flex-direction: column; justify-content: space-around;">
              <div style="font-size: 1.2em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                <div v-if="item.firstname&&item.firstname.length>=12">
                  <el-tooltip :open-delay="1000" placement="top">
                    <div slot="content">{{item.firstname}}</div>
                    <span>{{item.firstname.substring(0,9)+'...'}}</span>
                  </el-tooltip>
                </div>
                <div v-else>
                  {{item.firstname}}
                </div>
              </div>
              <div style="font-size: 0.8em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                <div v-if="item.lastname&&item.lastname.length>=12">
                  <el-tooltip :open-delay="1000" placement="top">
                    <div slot="content">{{item.lastname}}</div>
                    <span>{{item.lastname.substring(0,9)+'...'}}</span>
                  </el-tooltip>
                </div>
                <div v-else>
                  {{item.lastname}}
                </div>
              </div>
            </div>
          </div>
          <div style="padding: 0 5px 5px 5px; color: white;">
            <div :class="[item.class]"
                 style="font-size: 9px; height: 16px; line-height: 16px; white-space: nowrap;"
                 v-if="item.currentAction">
              {{ item.currentAction }}
              {{ item.currentAction === 'pto' ? getPtoTime(item) : durationformat(item) }}
            </div>
            <div :class="[item.class]"
                 style="font-size: 9px; height: 16px; line-height: 16px; white-space: nowrap;"
                 v-else>
              {{ $t('custom.attendance.board.unknown') }}
            </div>
          </div>
          <temaplte v-if="attendanceSchema.show_ticket">
            <!-- ticketInfo -->
            <div v-if="item.ticketInfo&&item.ticketInfo.isTicket !== 'unknown'"
                :class="{ticketinfo:true,'ticketinfo-border':item.ticketInfo.isTicket !== 'working'&&item.ticketInfo.isTicket }"
                :style="{ backgroundColor: computedBackgroundColor(item.ticketInfo),height:'30px'}">
              <div v-if="item.ticketInfo.isTicket === 'working'"
                  style="position: relative;display: flex;width: 100%;height: 100%;justify-content: center;align-items: center;padding: 6px 0;"
                  >
                <div style="color: #333;" >
                  <el-tooltip :open-delay="1000" effect="dark"
                              placement="bottom">
                    <div slot="content">
                      {{item.ticketInfo.priorityName}}
                      <p v-if="item.ticketInfo.companyName && attendanceSchema.show_company_name" style="margin:0">Company: {{item.ticketInfo.companyName}}</p>
                      <p v-if="item.ticketInfo.summary" style="margin:0">Summary: {{item.ticketInfo.summary}}</p>
                      <p v-if="item.ticketInfo.ownerName" style="margin:0">Ticket Owner: {{item.ticketInfo.ownerName}}</p>
                      <p v-if="item.ticketInfo.ticketResource" style="margin:0">Ticket Resource: {{item.ticketInfo.ticketResource}}</p>
                      <p style="margin:0">{{item.username}} changed the ticket to "{{item.ticketInfo.statusName}}" {{item.ticketInfo.time}} ago</p>
                    </div>
                    <span :class="{hiddenClass:!attendanceSchema.show_ticket}" v-if="item.ticketInfo.ticketNumber"
                          :style="{ color:computedColor(item.ticketInfo) }"
                          style="font-size:12px">
                      <span style="cursor:pointer;"
                            @click="openCwUrl(item.ticketInfo.cwUrl)">{{ item.ticketInfo.ticketNumber?item.ticketInfo.ticketNumber:item.ticketInfo.cwId }}</span>
                      / {{ item.ticketInfo.time }}
                    </span>
                    <span v-else
                          :style="{ color:computedColor(item.ticketInfo) }">
                      <span style="cursor:pointer;"
                            @click="openCwUrl(item.ticketInfo.cwUrl)">{{ item.ticketInfo.ticketNumber?item.ticketInfo.ticketNumber:item.ticketInfo.cwId }}</span>
                      / {{ item.ticketInfo.time }}
                    </span>
                  </el-tooltip>
                </div>
              </div>
              <div v-else-if="item.ticketInfo.isTicket"
                  style="position: relative;display: flex;width: 100%;height: 100%;justify-content: center;align-items: center;background: #3c578d;padding: 6px 0;">
                <div style="display: inline-flex; width: 100%; height: 100%; justify-content: center; align-items: center;color: #ffffff;">
                  {{ item.ticketInfo.isTicket }}
                </div>
              </div>
            </div>
          </temaplte>
          <template v-else>
            <div :style="{height:'29px',background:backgroundformat(item.action, item.subAction, item.timeout)}"></div>
          </template>
        </div>
      </div>
    </div>
    <BotPSASeeting ref="psa-setting-component" />
  </div>
</template>

<script>
import BotPSASeeting from '@/views/modules/mspbots/bots-bak/my-bots/bot-psa-setting'
import { debounce } from 'lodash'
import moment from 'moment'

export default {
  data () {
    return {
      loadingUserDataLists: false,
      searchForm: {
        member: null,
        managerId: null,
        recursive: false
      },
      userDataLists: [],
      memberLists: [],
      // timer: null,
      managerList: [],
      curSortS: 'status',
      curSortB: 'Asc'
    }
  },
  components: {
    BotPSASeeting
  },
  computed: {
    attendanceSchema () {
      return this.$store.state.attendance.schema
    },
    sortList () {
      return window.SITE_CONFIG['dictList'] ? window.SITE_CONFIG['dictList'].find(
        e => e.dictType === 'Attendance Sort'
      ).dataList.filter(v=>v.dictValue==='priority'?this.$store.state.user.psa==='CW':true) : []
    },
    // orderList () {
    //   return window.SITE_CONFIG['dictList'] ? window.SITE_CONFIG['dictList'].find(
    //     e => e.dictType === 'Attendance Order'
    //   ).dataList : []
    // },
  },
  created () {
    this.getDefaultTeamAndMember()
    this.createdDataList()
    this.getAttendanceOrder()
  },
  beforeDestroy () {
    // clearInterval(this.timer)
  },
  methods: {
    async getAttendanceOrder (data) {
      const params = {
        userId: sessionStorage.getItem('loginAsUserId')||this.$store.state.user.id,
        keyword: 'attendance_order'
      }
      const { data: res } = await this.$interface.system.getAttendanceOrder(params)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      if(res.data&&res.data.value){
        this.sortList.forEach(v=>{
          if(res.data.value.includes(v.dictValue)){
            this.curSortS=v.dictValue
            this.curSortB=res.data.value.replace(v.dictValue,'')
          }
        })
      }
      if(!data)return
      this.getUserLists()
    },
    async setAttendanceOrder () {
      this.loadingUserDataLists = true
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        userId: sessionStorage.getItem('loginAsUserId')||this.$store.state.user.id,
        keyword: 'attendance_order',
        value: this.curSortS+this.curSortB
      }
      const { data: res } = await this.$interface.system.setAttendanceOrder(params)
      if (res.code !== 0) {
        this.loadingUserDataLists = false
        return this.$message.error(res.msg)
      }
      this.getAttendanceOrder('update')
    },
    changeSortB () {
      this.curSortB=this.curSortB==='Asc'?'Desc':'Asc'
      this.setAttendanceOrder()
    },
    changeSortS () {
      this.setAttendanceOrder()
    },
    createdDataList () {
      this.getMemberLists()
      this.getManagerList()
      // this.getUserLists()
    },
    refreshDataList () {
      this.getMemberLists()
      this.getManagerList()
      this.getUserLists('update')
    },
    setMSPcwUrl (url) {
      // remove this MB-15663
      if (url) {
        if (this.$store.state.user.psa && this.$store.state.user.psa === 'CW') {
          var arr = url.split('=')
          var ticketId = arr[arr.length - 1]
          url = `/ConnectWiseTicketView?id=${ticketId}`
        }
      }
      return url
    },
    goIdleReportLink () {
      // this.$router.push({ path: 'AttendanceIdle', query: { pageid: 'attendance-idle' } })
    },
    getMemberLists () {
      const params = {
        status: 1,
        regSource: 1
      }
      this.$interface.schedule.getWorkScheduledUserListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.memberLists = res.data
        })
        .catch(() => { })
    },
    managerIdChange (e) {
      this.searchForm.managerId = e
      this.$nextTick(() => {
        if (this.searchForm.recursive) {
          this.recursiveChange(true)
        } else {
          this.saveDefaultTeamAndMember()
          this.getUserLists()
        }
      })
    },
    recursiveChange (e) {
      this.searchForm.recursive = e
      if (e) {
        if (!this.searchForm.managerId) {
          return this.$message.error('Please Select Manage')
        }
      }
      if (!this.searchForm.recursive) {
        this.searchForm.member = []
        this.$forceUpdate()
      }
      this.$nextTick(() => {
        this.getUserIdLists(this.searchForm.managerId)
      })
      this.saveDefaultTeamAndMember()
    },
    memberChange: debounce(function (e) {
      if (e && e.length > 0) {
        this.searchForm.member = e
      } else {
        if (this.searchForm.recursive) { this.searchForm.recursive = false }
      }
      this.$nextTick(() => {
        this.saveDefaultTeamAndMember()
        this.getUserLists()
      })
    }, 1000),
    getUserIdLists (data) {
      if (!data) {
        return
      }
      this.loadingUserDataLists = true
      const params = {
        datasetKey: 'b44dfc22-c71f-4c6f-8ba0-dcf62c78aa49',
        data: `managerid=${data}`
      }
      this.$interface.reports.getReportDatasetDataApi(params.datasetKey, params.data)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          let temp = []
          res.data.forEach(item => {
            temp.push(item.id)
          })
          if (!this.searchForm.recursive) {
            this.searchForm.member = []
          } else {
            this.searchForm.member = temp
          }
          this.getUserLists()
        })
        .catch(() => { this.loadingUserDataLists = false })
    },
    async get911FormListDetail () {
      const params = {
        current: 1,
        size: 1,
        desc: 'create_time',
        formCode: '1446360327431262208'
      }
      const { getFormDataListApi } = this.$interface.reports
      const { data } = await getFormDataListApi(params)
      return data.data && data.data.records.length > 0 ? data.data.records[0] : null
    },
    async getUserLists (e) {
      this.loadingUserDataLists = true
      if (e === 'update') {
        this.loadingUserDataLists = false
      }
      // const params = {
      //   tenantCode: this.$store.state.user.tenantCode
      // }
      // this.searchForm.managerId && (params.managerId = this.searchForm.managerId)
      // this.searchForm.member && this.searchForm.member.length > 0 && (params.userIds = this.searchForm.member.join(','))
      // if (this.searchForm.managerId && this.searchForm.managerId === '0') {
      //   params.recursive = false
      // } else {
      //   params.recursive = this.searchForm.recursive ? (params.recursive = this.searchForm.recursive) : this.searchForm.recursive
      // }
      const params = {
        datasetKey: '8c6bbed8-f922-4837-a7d4-25deeda0ff81',
        drillThrough: ''
      }
      if (this.searchForm.managerId) {
        if (this.searchForm.recursive) {
          if (this.searchForm.member && this.searchForm.member.length > 0) {
            params.drillThrough = `filter= userid in (${this.searchForm.member.join(',')})`
          }
        } else {
          params.drillThrough = `filter= managerid ='${this.searchForm.managerId}'`
          if (this.searchForm.member && this.searchForm.member.length > 0) {
            params.drillThrough = `filter= managerid ='${this.searchForm.managerId}' and userid in (${this.searchForm.member.join(',')})`
          }
        }
      } else {
        if (this.searchForm.member && this.searchForm.member.length > 0) {
          var str = ''
          this.searchForm.member.forEach((iii, index) => {
            if (index === this.searchForm.member.length - 1) {
              str += `'${iii}'`
            } else {
              str += `'${iii}',`
            }
          })
          params.drillThrough = `filter= userid in (${str})`
        }
      }
      const formDetail = await this.get911FormListDetail()
      if (formDetail && formDetail.dataContent && formDetail.dataContent.checkbox && formDetail.dataContent.checkbox.includes('911IT')) {
        params.data = `datasetLayerId=1567769106497126402&` + params.drillThrough
      } else {
        if (this.$store.state.user.psa) {
          switch (this.$store.state.user.psa) {
            case 'AUTOTASK':
              params.data = `datasetLayerId=1467758827847659522&` + params.drillThrough
              break
            case 'CW':
              params.data = params.drillThrough
              break
            case 'SYNCROMSP':
              params.data = `datasetLayerId=1581840924558172161&` + params.drillThrough
              break
            case 'KASEYAMSP':
              params.data = `datasetLayerId=1597862353676800001&` + params.drillThrough
              break
            case 'JIRAMSP':
              params.data = `datasetLayerId=1633755615907528706&` + params.drillThrough
              break
            default:
              params.data = params.drillThrough
          }
        }
      }


      this.$interface.reports.getReportDatasetDataApi(params.datasetKey, params.data)
        .then(({ data: res }) => {
          this.loadingUserDataLists = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.userDataLists = []
          let temp = []
          for (let index = 0; index < res.data.length; index++) {
            const element = res.data[index]
            temp.push({
              logTime: element.logtime,
              userId: element.userid,
              action: element.action,
              subAction: element.subaction,
              currentAction: element.currentaction,
              username: element.real_name,
              timeout: element.timeout,
              firstname: element.firstname,
              lastname: element.lastname,
              headerUrl: element.head_url,
              ptotime: element.ptotime,
              pto_endtime: element.pto_endtime,
              ticketInfo: {
                tenantCode: element.tenantcode,
                isTicket: element.is_ticket,
                cwId: element.cwid,
                priorityName: element.priorityname,
                time: element.time,
                cwUrl: element.cwurl,
                color: element.color,
                companyName: element.companyname,
                summary: element.summary,
                dataSource: element.datasource,
                ticketNumber: element.ticketnumber,
                ownerName: element.owner_name,
                statusName: element.status_name,
                ticketResource: element.ticket_resource
              }
            })
          }
          this.$nextTick(() => {
            this.userDataLists = temp
          })
        })
        .catch((e) => {
          this.loadingUserDataLists = false
        })
    },
    backgroundformat (action, subAction, timeout) {
      if (subAction === 'wfh') {
        return this.attendanceSchema.color_wfh
      }
      try {
        if ((action === 'in' && !subAction) || (action === 'in' && subAction === 'back')) {
          if (timeout) {
            return '#616161'
          } else {
            return this.attendanceSchema.color_in
          }
        } else if (action === 'out' && !subAction) {
          return this.attendanceSchema.color_tbfvywci
        } else if (action === 'out' && subAction) {
          if (timeout) {
            return '#616161'
          } else {
            if (subAction === 'onsite') {
              return this.attendanceSchema.color_onsite
            } else if (subAction === 'break') {
              return this.attendanceSchema.color_break
            } else if (subAction === 'lunch') {
              return this.attendanceSchema.color_lunch
            }
          }
        } else if (action === 'pto') {
          return this.attendanceSchema.color_pto
        }else {
          return '#9E9E9E'
        }
      } catch (error) {
        return '#9E9E9E'
      }
    },
    avatarFormat (username) {
      try {
        let avatar = ''
        if (username != null) {
          const nameArr = username.split(' ')
          for (let i = 0; i < nameArr.length; i++) {
            avatar += nameArr[i].substr(0, 1)
          }
        }
        return avatar.toUpperCase()
      } catch (error) {
        return ''
      }
    },
    onImgLoadError (avatarMsg) {
      if (avatarMsg) {
        if (event && event.target && event.target.parentElement) {
          event.target.parentElement.innerHTML = avatarMsg
        }
      }
    },
    getPtoTime (item) {
      return `: until ${item.pto_endtime}`
    },
    durationformat (item) {
      // logTime
      if (item.logTime) {
        const difftime = moment.tz().utc().diff(item.logTime, 'seconds')
        const tempTime = moment.duration(difftime, 'seconds')
        let time = ': '
        if (tempTime.asDays() > 0) {
          time += parseInt(tempTime.asDays()) + 'd '
        }
        if (tempTime.hours() > 0) {
          time += tempTime.hours() + 'h '
        }
        if (tempTime.minutes() > 0) {
          time += tempTime.minutes() + 'm'
        }
        if (tempTime.minutes() < 1) {
          time += '0m'
        }
        return time
      }
    },
    openCwUrl (url) {
      window.open(url, '_blank')
    },
    saveDefaultTeamAndMember () {
      localStorage.setItem('defaultTeamAndMember', JSON.stringify({ member: this.searchForm.member, managerId: this.searchForm.managerId, recursive: this.searchForm.recursive }))
    },
    getDefaultTeamAndMember () {
      try {
        const tempObj = JSON.parse(localStorage.getItem('defaultTeamAndMember'))
        this.searchForm.member = tempObj.member
        this.searchForm.managerId = tempObj.managerId
        this.searchForm.recursive = tempObj.recursive
      } catch (error) { }
    },
    computedColor (ticketInfo) {
      // if (!color) {
      //   return '#666666'
      // }
      let curItem=Array.isArray(this.attendanceSchema.textColor)&&this.attendanceSchema.textColor.find(v=>v.name===ticketInfo.priorityName)
      let defaultItem=Array.isArray(this.attendanceSchema.textColor)&&this.attendanceSchema.textColor.find(v=>v.name==='priority')
      if(curItem){
        return curItem.textColor||'#ffffff'
      }else{
        if (ticketInfo.color === 'Yellow' || ticketInfo.color === 'White' || ticketInfo.color === 'Cyan') {
          return '#666666'
        } else {
          return defaultItem?(defaultItem.textColor||'#ffffff'):'#ffffff'
        }
      }
    },
    computedBackgroundColor (ticketInfo) {
      if(!ticketInfo.isTicket)return
      if (ticketInfo.dataSource === 'AUTOTASK') {
        let color = null
        switch (ticketInfo.priorityName) {
          case 'Critical':
            color = '#E31F37'
            break
          case 'High':
            color = '#10C03A'
            break
          case 'Medium':
            color = '#F79E40'
            break
          case 'Low':
            color = '#666666'
            break
          default:
            color = '#0C6D72'
            break
        }
        return color
      } else {
        return ticketInfo.color ? ticketInfo.color : '#3c578d'
      }
    },
    getManagerList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.attendance.getManagerListApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.managerList = res.data
      }).catch(() => { })
    },
    openPSASetupDialog () {
      this.$refs['psa-setting-component'].openDialog()
    }
  }
}
</script>
<style lang="scss" scoped>
.sort-select{
  display: flex;
  float: right;
  align-items: center
}
@import "./attendance.scss";
.user-status-content {
  // border: 1px solid green;
 ::v-deep  .el-input--suffix .el-input__inner {
    height: 32px !important;
  }
  width: 100%;
  height: 100%;
  .ticketinfo{
    &-border{
      border-top:1px solid rgba(0, 0, 0, 0.22);
    }
    p{
      margin:0;
    }
    .hiddenClass{
      opacity: 0;
    }
  }
}
</style>
